<?php
declare (strict_types=1);

namespace app\platform\controller;

use think\facade\View;
use think\response\Json;

class Login extends PlatformBase
{
    public function index(): string
    {
        if ($this->isLogin()) {
            $this->redirect((string)url('index/index'));
        }

        return View::fetch();
    }

    public function check(): Json
    {
        if (!$this->request->isPost()) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_REQUEST_WAY_ERROR_MESSAGE);
        }

        $username = $this->request->param('username', '', 'trim');
        $password = $this->request->param('password', '', 'trim');
        $validate = (new \app\platform\validate\Merchant())->scene('login');
        $data     = [
            'username' => $username,
            'password' => $password,
        ];
        if (!$validate->check($data)) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), $validate->getError());
        }

        $merchantBusiness = new \app\platform\business\Merchant();
        $result           = $merchantBusiness->login($data);

        if ($result) {
            return show(config(self::_CONFIG_STATUS_SUCCESS_CODE), '登录成功');
        }

        return show(config(self::_CONFIG_STATUS_ERROR_CODE), '用户名或密码错误');
    }

    public function logout(): Json
    {
        $merchantBusiness = new \app\platform\business\Merchant();
        $merchantBusiness->logout();
        return show(config(self::_CONFIG_STATUS_SUCCESS_CODE), '退出');
    }
}
